# Copyright (c) 2024, cy080585@126.com and contributors
# For license information, please see license.txt
from frappe import _
import frappe
from zy_packlist.zy_packlist.controllers.pack_listdoc import PackListDoc
from zy_packlist.zy_packlist.doctype.packing_list.packing_list import get_packing_items_ledgers,add_packing_items_ledgers


class PackingOrder(PackListDoc):
	def before_save(self):
		super().before_save()
		for item in self.items:
			if item.old_packing_list_items and not item.packing_list_items:
				res=get_packing_items_ledgers(item.old_packing_list_items)
				packing_list_doc=add_packing_items_ledgers(res,item,self)
				item.packing_list_items=packing_list_doc.name
				item.old_packing_list_items=packing_list_doc.name
	

	def on_cancel(self):
		# self.flags.ignore_links=True

		if self.status=="Completed":
			frappe.throw(_('Cannot cancel completed documents'))
		super().on_cancel()


@frappe.whitelist()
def get_packing_order_details(packing_order,as_dict=False):
	doc_status = frappe.db.get_value("Packing Order", packing_order, "docstatus")
	join_cloumn="packing_list_items"
	if doc_status == 2:
		join_cloumn='old_packing_list_items'

	sql=f"""
		SELECT tpoi.marks_no ,tpli.item_code ,tpli.item_name ,tpli.`size`,tpli.qty,tpli.stock_uom,tpli.rate,tpli.amount,
		tpli.net_weight,tpoi.net_weight_pkg
		 ,tpoi.gross_weight_pkg,tpoi.packages_no,tpoi.carton_measure
		FROM  `tabPacking Order Item` tpoi 
		left join `tabPacking Order` tpo  on tpoi.parent=tpo.name 
		left join `tabPacking List Item` tpli on tpoi.{join_cloumn} =tpli.parent 
		where tpo.name =%s
		order by tpoi.idx asc
	"""
	item_details=frappe.db.sql(sql,(packing_order,),as_dict=as_dict)
	return  {"items":item_details}



# 按照excel格式导入方法
@frappe.whitelist()
def import_parking_order(file_path):
	from zy_packlist.utils import upload_xlsx_file
	packing_list=upload_xlsx_file(file_path)
	# packing_order_list=frappe.parse_json(packing_order_list)
	table_head=[]
	table_body={}
	items=[]
	pre_marks_no=None
	pre_item_code=None
	for row in packing_list:
		if pre_marks_no != row["marks_no"] and row["marks_no"] :
			table_head.append({
				"marks_no":row["marks_no"],
				"net_weight_pkg":float(row["net_weight_pkg"]) or 0,
				"gross_weight_pkg":float(row["gross_weight_pkg"]) or 0,
				"packages_no":row["packages_no"] or 0,
				"carton_measure":row["carton_measure"] or 0,
				"cbm":row["cbm"] or 0,
			})
			pre_marks_no=row["marks_no"]

			table_body[row["marks_no"]]=[]

			table_body[row["marks_no"]].append({
				"item_code":row["item_code"],
				"item_name":row["item_name"],
				"size":row["size"],
				"qty":int(row["qty"] or 0 ) ,
				"stock_uom":row["stock_uom"],
				"rate":float(row["rate"] or 0),
				"amount":float(row["amount"] or 0 ) ,
				"net_weight":float(row["net_weight"] or 0) ,
				"customs_item_code":row["customs_item_code"],
			})
		else:
			table_body[pre_marks_no].append({
				"item_code":row["item_code"],
				"item_name":row["item_name"],
				"size":row["size"],
				"qty":int(row["qty"] or 0 ),
				"stock_uom":row["stock_uom"],
				"rate":float(row["rate"] or 0) ,
				"amount":float(row["amount"] or 0 ) ,
				"net_weight":float(row["net_weight"] or 0) ,
				"customs_item_code":row["customs_item_code"],
			})

		if pre_item_code != row["item_code"] and row["item_code"] :
			items.append({
				"item_code":row["item_code"],
				"item_name":row["item_name"],
				"size":row["size"],
				"stock_uom":row["stock_uom"],
				"net_weight":float(row["net_weight" or 0] /float(row['qty'] or 1)) ,
			})
			pre_item_code=row["item_code"]

	
	uom_names={row["stock_uom"] for row in items}
	names=frappe.db.get_list("UOM",{'uom_name':['in',uom_names]},pluck='name')

	for uom_name in uom_names:
		if uom_name not in set(names):
			uom_doc=frappe.new_doc('UOM')
			uom_doc=uom_doc.update({
				'uom_name':uom_name
				}).save()


	item_codes={item["item_code"] for item in items}
	item_names=frappe.db.get_list("Item",{'item_code':['in',item_codes]},pluck='name')
	for row in items:
		if row["item_code"] not in set(item_names):
			item_doc=frappe.new_doc('Item')
			item_doc=item_doc.update({
				'item_code':row["item_code"],
				'item_name':row["item_name"],
				"stock_uom":row["stock_uom"],
				"item_group":'goods',
				"custom_size":row["size"],
				"custom_unit_weight":row["net_weight"]
				}).save()


	return {
	"table_head":table_head,
	"table_body":table_body
	}

from zy_packlist.zy_packlist.doctype.packing_list.packing_list import add_packing_items_ledgers 

# 由Packing Order 创建 Packing Process
@frappe.whitelist()
def create_packing_process(order_list):
	order_list=frappe.parse_json(order_list)
	packing_orders=frappe.get_list("Packing Order",filters={"name":['in',order_list]},
								fields=['name','customer','customer_name','docstatus','currency','status'])
	pre_customer=None
	pre_currency=None
	pre_customer_name=None
	errors=[]
	for row in packing_orders:
		if row.docstatus == 1:
			if  row.status == 'Completed':
				frappe.throw(_("Must be a submitted but incomplete document ")+ row.name)
		else:
			frappe.throw(_("Must be a submitted  document ")+ row.name)
	
		if pre_customer is None:
			pre_customer = row.customer
			pre_customer_name=row.customer_name
		elif pre_customer != row.customer:
			frappe.throw(f"All orders must have the same customer. Mismatch found in order {row.name} with customer {row.customer}.")
		
		if pre_currency is None:
			pre_currency = row.currency
		elif pre_currency != row.currency:
			frappe.throw(f"All orders must have the same currency. Mismatch found in order {row.name} with currency {row.currency}.")
	
	# if errors:
	# 	frappe.throw('<br>'.join(errors))


	packing_orders=frappe.get_list("Packing Order",filters={"name":['in',order_list]},
							fields=['name as order_name','`tabPacking Order Item`.marks_no','`tabPacking Order Item`.net_weight_pkg',
			   '`tabPacking Order Item`.gross_weight_pkg','`tabPacking Order Item`.packages_no','`tabPacking Order Item`.carton_measure',
			   '`tabPacking Order Item`.cbm','`tabPacking Order Item`.packing_list_items','`tabPacking Order Item`.name as order_item_name'])

	doc=frappe.new_doc("Packing Process")
	doc.update({
		"customer":pre_customer,
		"currency":pre_currency,
		"customer_name":pre_customer_name,
	     })

	for row in packing_orders:
		item={
			"doctype":"Packing Process Item",
			"order_name":row.order_name,
			"marks_no":row.marks_no,
			"net_weight_pkg":row.net_weight_pkg,
			"gross_weight_pkg":row.gross_weight_pkg,
			"packages_no":row.packages_no,
			"carton_measure":row.carton_measure,
			"cbm":row.cbm,
			"order_packing_list_item":row.packing_list_items,
			"order_item_name":row.order_item_name,
			"packing_list_items":'',
			"parenttype":"Packing Process",
			}

		packlist_items=frappe.get_all("Packing List Item",filters={"parent":row.packing_list_items},fields=['item_code','item_name','stock_uom','net_weight','qty','rate','amount','size','customs_item_code','name as order_item_name','parent as order_name'])
		packing_list_doc=add_packing_items_ledgers(packlist_items,frappe._dict(item),doc)
		item['packing_list_items']=packing_list_doc.name
		item['old_packing_list_items']=packing_list_doc.name
		doc.append("items",item)
	doc.save()
	return doc